package com.ifnk.portaljava.hlyt.etl;

import com.ifnk.portaljava.hlyt.etl.beans.GnData;
import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.util.ArrayList;

/**
 * <p>Title:发送数据到浏览器的类 </p>
 *
 * <p>Description: 将数据发往浏览器</p>
 *
 * <p>Copyright: Copyright (c) 2010</p>
 *
 * <p>Company: </p>
 * 
 * @author chengzhang.shi.hlyt@gmail.com
 * @version 1.0
 */
public class DataToFlexTask implements Runnable {

	private Log loger = LogFactory.getLog(DataToFlexTask.class);
	private File workDir = null;
	private String[] clientIds = {};

	public void run() {
		File[] files = workDir.listFiles();
		ArrayList<GnData> datas = new ArrayList<GnData>();
		System.out.println("files.length:"+files.length);
		for (int i = 0; i < files.length; i++) {
			GnFile gf = new GnFile();
			boolean flag = gf.setFile(files[i]);
			if(flag) {
				datas.addAll(gf.getDatas());
			}
			files[i].delete();
		}
		StringBuffer sb = new StringBuffer();
		for (int j = 0; j < clientIds.length; j++) {
			sendPacketToFlex("etlChannel" + clientIds[j], clientIds[j], datas);
			sb.append(":");
			sb.append(clientIds[j]);
		}
		loger.info("向页面" + sb.toString() + "发送数据：" + datas);
		workDir.delete();
	}

	public void sendPacketToFlex(String subTopic, String clientId, Object obj) {
		// loger.info("sendPacketToFlex");
		MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
		AsyncMessage msg = new AsyncMessage();
		msg.setDestination("etlChannel");
		msg.setHeader("DSSubtopic", subTopic);
		msg.setClientId(clientId);
		msg.setMessageId(UUIDUtils.createUUID());
		msg.setTimestamp(System.currentTimeMillis());
		msg.setBody(obj);
		messageBroker.routeMessageToService(msg, null);
	}

	public File getWorkDir() {
		return workDir;
	}

	public void setWorkDir(File workDir) {
		this.workDir = workDir;
	}

	public String[] getClientIds() {
		return clientIds;
	}

	public void setClientIds(String[] clientIds) {
		this.clientIds = clientIds;
	}

}
